<?php

class Project_model extends MY_Model {

	public function __construct() {
		parent::__construct();
		$this->table = 'alsa_project';

		$this->as = 'p';

		$this->relations = array(
			array(
				'table' => 'alsa_project_category',
				'as' => 'c',
				'foreign' => 'id',
				'local' => 'category',
				'type' => 'left'
			),
			array(
				'table' => 'alsa_node',
				'as' => 'n',
				'foreign' => 'id',
				'local' => 'cover',
				'type' => 'left'
			)
		);

		$this->columns = array(
			'*', array('n.name', 'cover_name'), array('c.name_zh', 'category_name')
		);
	}

	public function rand($lang, $category = 0, $ids = array(), $limit = 1) {
		$where_sql = array();

		if ($category > 0) {
			$where_sql[] = " where p.category like '%.{$category}.%'";
		}

		if (!empty($ids)) {
			$where_sql[] = (empty($where_sql) ? ' where' : ' and') . ' p.id not in (' . implode(',', $ids) . ')';
		}

		$where = implode(' ', $where_sql);

		$sql = "select
		    p.id as id,
		    p.name_{$lang} as name,
			p.summary_{$lang} as summary,
		    n.name as cover_name
		from alsa_project p
		left join alsa_node n
		    on p.cover=n.id
		{$where}
		order by rand()
		limit {$limit}";

		$query = $this->db->query($sql);

		if ($limit == 1)
			return $query->row();
		else
			return $query->result();
	}

}
